package com.luffy.devops

/**
 *
 * @param repo Harbor地址（包括项目名称），可以从环境变量 中获取
 * @param tag 构建镜像时的版本
 * @param credentialsId 登陆Harbor的凭证ID
 * @param appName 应用名称
 * @param fileId Docker全局配置文件id
 * @param dockerfile Dockerfile文件名称
 * @param context Dockerfile文件上下文
 * @return
 */
def init(String repo, String tag, String credentialsId, String appName, String fileId, String dockerfile="Dockerfile", String context="."){
    this.repo = repo
    this.tag = tag
    this.dockerfile = dockerfile
	this.fileId = fileId
    this.credentialsId = credentialsId
    this.appName = appName
	this.context = context
    if(env.TAG_NAME){
        this.tag = env.TAG_NAME
    }
	
    this.fullAddress = this.repo.endsWith("/") ? "${this.repo}${this.appName}:${this.tag}" : "${this.repo}/${this.appName}:${this.tag}"
    this.isLoggedIn = false
    this.msg = new BuildMessage()
    return this
}


/**
 * 构建镜像
 * @return
 */
def build() {
    this.login()
    def isSuccess = false
    def errMsg = ""
    retry(3) {
		configFileProvider([configFile(fileId: "${this.fileId}", targetLocation: "${this.dockerfile}")]){
			try {
				sh "docker build -t ${this.fullAddress} -f ${this.dockerfile} ${this.context}"
				isSuccess = true
			}catch (Exception err) {
				//ignore
				errMsg = err.toString()
			}
			// check if build success
			def stage = env.STAGE_NAME + '-build'
			if(isSuccess){
				updateGitlabCommitStatus(name: "${stage}", state: 'success')
				this.msg.updateBuildMessage(env.BUILD_TASKS, "${stage} OK...  √")
			}else {
				updateGitlabCommitStatus(name: "${stage}", state: 'failed')
				this.msg.updateBuildMessage(env.BUILD_TASKS, "${stage} Failed...  x")
				// throw exception，aborted pipeline
				error errMsg
			}
		}
        

        return this
    }
}


/**
 * 想Harbor推送镜像
 * @return
 */
def push() {
    this.login()
    def isSuccess = false
    def errMsg = ""
    retry(3) {
        try {
            sh "docker push ${this.fullAddress}"
            env.CURRENT_IMAGE = this.fullAddress
            isSuccess = true
        }catch (Exception err) {
            //ignore
            errMsg = err.toString()
        }
    }
    // check if build success
    def stage = env.STAGE_NAME + '-push'
    if(isSuccess){
        updateGitlabCommitStatus(name: "${stage}", state: 'success')
        this.msg.updateBuildMessage(env.BUILD_TASKS, "${stage} OK...  √")
    }else {
        updateGitlabCommitStatus(name: "${stage}", state: 'failed')
        this.msg.updateBuildMessage(env.BUILD_TASKS, "${stage} Failed...  x")
        // throw exception，aborted pipeline
        error errMsg
    }
    return this
}

/**
 * 登陆Harbor
 * @return
 */
def login() {
    if(this.isLoggedIn || credentialsId == ""){
        return this
    }
    // docker login
    withCredentials([usernamePassword(credentialsId: this.credentialsId, usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        def regs = this.getRegistry()
        retry(3) {
            try {
                sh "echo $PASSWORD | docker login -u $USERNAME ${regs} --password-stdin"
            } catch (Exception ignored) {
                echo "docker login err, ${ignored.toString()}"
            }
        }
    }
    this.isLoggedIn = true;
    return this;
}

/**
 * 获取Harbor的URL地址
 * @return
 */
def getRegistry(){
    def sp = this.repo.split("/")
    if (sp.size() > 1) {
        return sp[0]
    }
    return this.repo
}